import logging.config
from pynput.mouse import Controller as mController
from pynput.keyboard import Controller as kController
from pynput.keyboard import Key
import functools
import cv2
import numpy
import numpy as np
from PIL import ImageGrab, Image,ImageEnhance
import time
from cnocr import CnOcr
from datetime import datetime


# https://github.com/breezedeus/CnOCR
# 将来简化一点代码
def sleep(s):
    # 唯一一个地方的例外
    time.sleep(s)
    return

def clean_point(grey0, degree=200):
        grey = grey0.copy()                                   #创建一个副本 以免去除噪点后影响后续点的计算
        for x in range(1, len(grey) - 1):
            for y in range(1, len(grey[x]) - 1):
                mar = grey[x - 1:x + 2, y - 1: y + 2]        #取得点（x,y）及周围八个点
                if mar[mar > degree].size > 5:              #灰度值大于200的点的个数大于5就认为是噪点
                    grey0[x][y] = 255
        return grey0[1:-1, 1:-1]

sleep(5)
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"))
start = time.time()
#ocr = CnOcr()
# ocr = CnOcr(det_model_name='en_PP-OCRv3_det')
# ocr = CnOcr(rec_model_name='densenet_lite_114-fc')
ocr = CnOcr(det_model_name='en_PP-OCRv3_det')

# 魔兽图像的血量的绝对坐标
x1 = 266
y1 = 788
x2 = 408
y2 = 831
# imTopBlood = ImageGrab.grab(
#     bbox=(x1, y1, x2,
#           y2))  # X1,Y1,X2,Y2
# d:/yehaiboxx.jpg
imTopBlood1 = Image.open(r'd:/yehaibo_Blood.jpg')
#小于220，赋值为255，其他值为0
_, syn_binary_inv = cv2.threshold(np.asarray(imTopBlood1), 230, 255, cv2.THRESH_BINARY_INV)
 
#大于220，赋值为255，其他值为0
_, syn_binary = cv2.threshold(np.asarray(imTopBlood1), 230, 255, cv2.THRESH_BINARY) 
# imTopBlood = ImageEnhance.Contrast(imTopBlood1).enhance(2.0)

cv2.imshow("cell", syn_binary)
cv2.waitKey(0)
gray = cv2.cvtColor(numpy.asarray(syn_binary), cv2.COLOR_BGR2GRAY)
binary = cv2.adaptiveThreshold(~gray, 255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 15, -10)
yehaiboclean = clean_point(gray,230)

cv2.imshow("cell", yehaiboclean)
cv2.waitKey(0)
cv2.imwrite(r'd:/yehaiboxx2.jpg',yehaiboclean)

#res = ocr.ocr(r'd:/yehaibo_Blood.jpg')
# numpy.asarray(imTopBlood)
res = ocr.ocr(yehaiboclean)
wowStr = ''
# print(res[0][0])
for everyOne in res:
    wowStr = everyOne['text']
    print(wowStr)
#     for everyOne in list:
#         #for everyChar in everyOne:
#         print('1')
#         print(everyOne)
# wowStr = wowStr + str(everyChar)
# print(wowStr)
end = time.time()
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"))
print("花费的秒数:" + str(end - start))
